package com.his.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.his.api.service.PatientService;
import com.his.dao.domain.dto.ListDto;
import com.his.dao.domain.entity.Patient;
import com.his.dao.domain.vo.ListVo;
import com.his.dao.domain.vo.LoginVo;
import com.his.dao.mapper.PatientMapper;
import com.his.util.constant.RedisConstant;
import com.his.util.result.RestResult;
import com.his.util.result.RestResultBuilder;
import com.his.util.util.MapUtil;
import com.his.util.util.StringUtil;
import com.his.util.util.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;

import static com.his.util.constant.RedisConstant.*;
import static com.his.util.constant.RedisConstant.USER;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fall
 * @since 2022-11-28
 */
@Service
@AllArgsConstructor
public class PatientServiceImpl extends ServiceImpl<PatientMapper, Patient> implements PatientService {
    private PatientMapper patientMapper;
    private RedisTemplate redisTemplate;

    @Override
    public RestResult login(Patient patient) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<Patient>()
                .eq("username", patient.getUsername())
                .eq("password", patient.getPassword());
        patient = patientMapper.selectOne(queryWrapper);

        if (patient == null) {
            return new RestResultBuilder().fail();
        }

        String authorization = TokenUtil.getInstance().makeToken();

        // 存放用户token
        redisTemplate.opsForValue().set(REDIS_FOLDER + PATIENT + patient.getPatientId(), authorization, 1, TimeUnit.HOURS);
        // 存放用户id
        redisTemplate.opsForValue().set(getPatientAndAuthorization(authorization), PATIENT + patient.getPatientId(), 1, TimeUnit.HOURS);
        return new RestResultBuilder().success(LoginVo.builder().authorization(authorization).build());
    }

    @Override
    public RestResult info(String authorization) {
        Integer userId = StringUtil.getId(PATIENT, (String) redisTemplate.opsForValue().get(getPatientAndAuthorization(authorization)));

        QueryWrapper<Patient> queryWrapper = new QueryWrapper<Patient>()
                .select("name")
                .eq("patient_id", userId);
        return new RestResultBuilder().success(patientMapper.selectOne(queryWrapper));
    }
}
